const api = require('./util');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//判断用户登录
function isLogin(){
  var userInfo = wx.getStorageSync('userInfo');
    if(!userInfo){
      wx.showModal({
        title: '登录提示',
        content: '请先去登录',
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '../personal/index',
            })
          } else if (res.cancel) {
          }
        }
      })
      return;
    }
}

//请求接口封装
function wxrequest(params){
  wx.request({
    url: params.url,
    dataType: 'json',
    data: params.data,
    method: params.method,
    success: (res) => {
      console.log(res);
      if (res.statusCode != 200){
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
        return;
      }
      if (params.success){
        params.success(res.data.data);
      }
    }
  })
}
//j将购物车商品添加到缓存
function addCart(product){
  //获取购物车信息
  var isHave = false;
  var carts = wx.getStorageSync('carts')?  wx.getStorageSync('carts'): [];
  if(carts) for(var index in carts){
    if(carts[index].id == product.id){
      isHave = true;
    }
  }
  if(!isHave){
    console.log(carts);
    carts.push(product)
    wx.setStorageSync('carts', carts)
  }else{
    wx.showToast({
      title: '购物车已经存在该商品，快去下单吧！',
      icon: 'none'
    })
    return;
  }
  //这里将购物车信息设置到缓存中
  wx.showToast({
    title: '添加成功',
  })
}

module.exports = {
  formatTime: formatTime,
  addCart: addCart,
  request: wxrequest,
  isLogin: isLogin
}
